import React, { Component, useRef, useState } from 'react'
import axios from 'axios';
import { Form, Input, DatePicker, Space, Button, InputNumber, Tabs, Radio, Select, Spin } from 'antd'
import { SearchOutlined, WalletOutlined, WechatOutlined, AlipayOutlined, PayCircleOutlined, UnorderedListOutlined } from "@ant-design/icons";
import _ from 'lodash'
import { getDateTime3 } from '@/utils/getDate'
import TheTable from '@/components/TheTable'
import ThePagination from '@/components/ThePagination'
import TheButton from '@/components/TheButton'
import CashierModal from '../component/CashierModal'
import TheImage from '@/components/TheImage'
import thirdParty from '@/assets/images/thirdParty.png'
import '../style/style.less'
import { apiGetStandOrderPage, apiExportLibraryOutReport, apiOrderExportCapitalDaily, apiGetOrderExportOrder, apiGetStandOrderDetail, apiStandOrderDetail, apiStandSalesReturn, apiStandSalesReturnOrder, apiGetSalesmanList, apiStandOrderSettlement, apiStandOrderCancel, apiOrderPollingPayResult, apiHotelOrderInfoPollingPayResult } from '@/request/cashier'
import finish from '@/assets/images/finish.png'
import { exportSheetTable, exportTableModal } from '@/utils/exportTable'
import moment from 'moment'
import QRCode from "qrcode.react";
import logoUrl from '@/assets/images/logoIcon.png'
import Json2Excel from '@/utils/Json2Excel.js'
const { RangePicker } = DatePicker;
const { TabPane } = Tabs
const SearchHeader = ({ getValue, exportExcel, exportDay, exportOrder, exportLoading, exportSaleOutTable, orderState }) => {
  const formRef = useRef()
  const onFinish = (values) => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0])
      values.createTimeEnd = getDateTime3(values.time[1])
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    getValue(values)
  }
  const exportSheet = () => {
    exportExcel(formRef.current.getFieldValue())
  }
  const exportDayFile = async () => {
    await exportDay(formRef.current.getFieldValue())
  }
  const exportSaleOut = async () => {
    await exportSaleOutTable(formRef.current.getFieldValue())
  }
  const exportDayOrder = async () => {
    await exportOrder(formRef.current.getFieldValue())
  }

  const reset = () => {
    formRef.current.setFieldsValue({
      orderCode: '',
      time: []
    })
    getValue({})
  }
  return <Form layout={'inline'} onFinish={onFinish} ref={formRef}>
    <Form.Item name="orderCode">
      <Input suffix={<SearchOutlined />} placeholder="订单编号" />
    </Form.Item>
    <Form.Item label="订单时间" name={'time'}>
      <RangePicker />
    </Form.Item>
    <Form.Item>
      <Space>
        <Button type='primary' htmlType='submit'>搜索</Button>
        <Button onClick={reset}>重置</Button>
      </Space>


    </Form.Item>
    {orderState === '9' ? <TheButton size="middle" type="default" hasPermi={['cashier:order:exportOrder']} onClick={exportSheet} loading={exportLoading}>导出订单</TheButton> : null}
    {orderState === '9' ? <TheButton size="middle" type="default" hasPermi={['cashier:order:exportDaily']} onClick={exportDayFile} loading={exportLoading}>导出资金日报表</TheButton> : null}
    {orderState === '9' ? <TheButton size="middle" type="default" hasPermi={['cashier:order:exportDailyOrder']} onClick={exportDayOrder} loading={exportLoading}>导出资金日报订单</TheButton> : null}
    {orderState === '9' ? <TheButton size="middle" type="default" hasPermi={['cashier:order:exportSales']} onClick={exportSaleOut} loading={exportLoading}>销售出库单导出</TheButton> : null}


  </Form>
}

export default class Order extends Component {
  roleIds = sessionStorage.getItem('roleName')
  code = ''
  lastTime = ''
  nextTime = ''
  lastCode = ''
  nextCode = ''
  state = {

    columns: [
      {
        title: '订单编号',
        dataIndex: 'orderCode',
        key: 'orderCode'
      },
      {
        title: '用户昵称',
        dataIndex: 'orderMemberName',
        key: 'orderMemberName',
        render: (text, record) => {
          return text || '无'
        }
      },
      {
        title: '实收金额',
        dataIndex: 'orderPayPrice',
        key: 'orderPayPrice',
        render: (text, record) => {
          return <React.$Price price={text} />
        }
      },
      {
        title: '付款方式',
        dataIndex: 'payWay',
        key: 'payWay',
        render: (text, record) => {
          return this.getPayWay(text)
        }
      },
      {
        title: '赠送积分',
        dataIndex: 'presentIntegral',
        key: 'presentIntegral',
        render: (text, record) => {
          return _.toNumber(text).toLocaleString()
        }
      },
      {
        title: '收款人员',
        dataIndex: 'cashierName',
        key: 'cashierName'
      },
      {
        title: '导购人员',
        dataIndex: 'shoppingGuideName',
        key: 'shoppingGuideName',
        render: (text, record) => {
          return text || '无'
        }
      },
      {
        title: '付款时间',
        dataIndex: 'createTime',
        key: 'createTime'
      },
      {
        title: '操作',
        fixed: 'right',
        render: (text, record) => {
          return <>
            <TheButton hasPermi={['cashier:order:view']} onClick={() => this.props.history.push(`/cashier/order/details/${record.orderId}`)}>查看订单</TheButton>
            {record.orderState === '1' ? <TheButton hasPermi={['cashier:order:continue']} onClick={() => this.continueOrder(record.orderId)}>继续收款</TheButton> : null}
            {record.orderState === '9' ?
              _.toNumber(record.salesReturnStatus) === 0 && <TheButton hasPermi={['cashier:order:refund']} onClick={() => this.openDialog(record.orderId)}>退货退款</TheButton> : null
            }
            {record.orderState === '9' ?
              _.toNumber(record.salesReturnStatus) === 1 && <TheButton hasPermi={['cashier:order:chargebackDetail']} onClick={() => this.props.history.push(`/cashier/order/chargeback/${record.orderId}`)}>退款详情</TheButton> : null}
          </>
        }
      },
    ],
    dataSource: [],
    pageData: {
      pageNo: 1,
      pageSize: 10
    },
    total: 0,
    chargebackCommodityData: [],
    chargebackServiceData: [],
    totalReturnCount: 0,
    totalReturnPrice: 0,
    totalReturnIntegral: 0,
    returnVisible: false,
    returnData: [],
    standSalesReturnId: '',
    exportTableData: [],
    exportTablePay_way: [],
    exportLoading: false,
    orderState: '9',
    collectionData: [],
    payWayData: [],
    payWay: 'Cash',
    slaesmanData: [],
    commoditySelectData: [],
    shoppingGuideId: '',
    collectionVisible: false,
    orderId: "",
    cancelRemark: '订单异常关闭',
    thirdLoading: false,
    rejectLoading: false,
    scanCode: false,
    remoteAlipayVisible: false,
    remoteAlipayResultVisible: false,
    remoteAlipayResultLoading: false,
    payWayDescription: '',
    remoteWeChatVisible: false,
    remoteWeChatResultVisible: false,
    remoteWeChatResultLoading: false,
    remoteWeChatQrCodeStr: '',
    __html: '',
    couponDiscountTotal: '',
    productMaxOutPrice: ''
  }
  componentDidMount() {
    window.addEventListener('keypress', this.scanWrapper, false);
    this.getData()
    this.getSalesmanData()
  }
  componentWillUnmount() {
    window.removeEventListener('keypress', this.scanWrapper, false);
  }
  getData = async () => {
    this.setState({ loading: true })
    let { pageData, searchValue, orderState } = this.state
    let res = await apiGetStandOrderPage({ ...pageData, ...searchValue, orderState })
    if (res.data && res.code === 0) {
      this.setState({
        dataSource: res.data,
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount
      })
    }
    this.setState({ loading: false })
  }
  //扫码枪
  scanWrapper = async (e) => {
    // console.log(e)
    this.nextCode = e.which;
    this.nextTime = new Date().getTime();

    if (this.lastCode != null && this.lastTime != null && this.nextTime - this.lastTime <= 30) {
      this.code += String.fromCharCode(this.lastCode);
    } else if (this.lastCode != null && this.lastTime != null && this.nextTime - this.lastTime > 100) {
      this.code = '';
    }
    // console.log(e.which)
    this.lastCode = this.nextCode;
    this.lastTime = this.nextTime;
    // console.log(this.code)
    if (e.which === 13 && this.code) {
      //支付扫码
      const { commoditySelectData, orderId, scanCode } = this.state
      if (scanCode) {
        if (orderId) {
          let aliPay = ['25', '26', '27', '28', '29', '30']
          let weChatPay = ['10', '11', '12', '13', '14', '15']
          let startTwoCode = this.code.slice(0, 2)
          let payWay = this.state.payWay
          let visible = ''

          if (payWay === 'Alipay') {
            if (!aliPay.includes(startTwoCode)) {
              return React.$message({
                type: 'info',
                content: '请出示正确的付款码'
              })
            } else {
              visible = 'aliPayVisible'
            }
          }
          if (payWay === 'WeChat') {
            if (!weChatPay.includes(startTwoCode)) {
              return React.$message({
                type: 'info',
                content: '请出示正确的付款码'
              })
            } else {
              visible = 'weChatVisible'
            }
          }
          this.setState({ payWay, payCode: this.code }, () => this.payWaySettlement(visible))
        } else {
          let idArr = commoditySelectData.map(v => v.propCodeArray)
          if (idArr.includes(this.code)) {
            let arr = commoditySelectData.map(v => {
              if (v.propCodeArray === this.code) {
                if (_.toNumber(v.skuStock) === _.toNumber(v.count)) {
                  return v
                } else {
                  return {
                    ...v,
                    count: _.toNumber(v.count) + 1
                  }
                }
              } else {
                return v
              }
            })
            this.setState({
              commoditySelectData: arr
            }, () => {
              this.getCombined()
            })
          } else {
            let res = await React.$get(`/management/productInfo/getProductSkuDetailByCode/${this.code}`)
            if (res.code === 0 && res.data) {
              if (parseInt(res.data.skuStock)) {
                let arr = [
                  {
                    ...res.data,
                    productSkuSpecValue: res.data.skuAttribute.map(v => {
                      return v.product_value
                    }).join(';'),
                    count: 1
                  },
                  ...this.state.commoditySelectData
                ]
                this.setState({
                  commoditySelectData: arr
                }, () => this.getCombined())
              } else {
                React.$message({
                  type: 'info',
                  content: '商品库存不足'
                })
              }
            }
          }
        }
        this.code = '';
      }
    }
  }
  //获取导购员
  getSalesmanData = async () => {
    let res = await apiGetSalesmanList()
    if (res.data && res.code === 0) {
      let data = res.data.map(v => {
        return {
          label: v.shoppingGuideName,
          value: v.shoppingGuideId
        }
      })
      data.unshift({
        label: '无',
        value: ''
      })
      this.setState({
        slaesmanData: data
      })
    }
  }
  changeKey = key => {
    this.setState({
      orderState: key,
      pageData: {
        pageNo: 1,
        pageSize: 10
      },
    }, () => {
      this.getData()
    })
  }
  rejectReamkeChange = e => {
    this.setState({ cancelRemark: e.target.value })
  }
  initData = (data) => {
    console.log(data);
    let collectionData = [
      {
        title: '服务费用',
        value: <React.$Price price={data.orderServicePrice} />
      },
      {
        title: '商品费用',
        value: <React.$Price price={data.orderProductPrice} />
      },
      {
        title: '其他费用',
        value: <React.$Price price={data.otherServicePrice} />
      },
      {
        title: '收费原因',
        value: data.remark
      },
      {
        title: '赠送积分',
        value: data.presentIntegral
      },
      {
        title: '应收金额',
        value: <React.$Price color="#EF3800" price={data.orderServicePrice + data.orderProductPrice + data.otherServicePrice} />
      },
      {
        title: '待收金额',
        value: <React.$Price color="#EF3800" price={data.orderDueInyPrice} />
      },
      {
        title: '折扣立减',
        value: <React.$Price color="#EF3800" price={data.couponTotal} />
      },
      {
        title: '优惠金额',
        value: <React.$Price color="#EF3800" price={data.productMaxOutPrice || 0} />
      },
      {
        title: '优惠券立减',
        value: <React.$Price color="#EF3800" price={data.couponDiscountTotal} />
      },
    ]
    let payWayData = data.payWay.map(v => {
      let obj = {}
      switch (v) {
        case 'Cash':
          obj = {
            title: '现金',
            icon: <WalletOutlined />,
            value: 'Cash'
          }
          break;
        case 'Other':
          obj = {
            title: '其它',
            icon: <UnorderedListOutlined />,
            value: 'Other'
          }
          break;
        case 'Alipay':
          obj = {
            title: '支付宝',
            icon: <AlipayOutlined />,
            value: 'Alipay'
          }
          break;
        case 'WeChat':
          obj = {
            title: '微信',
            icon: <WechatOutlined />,
            value: 'WeChat'
          }
          break;
        case 'Wallet':
          obj = {
            title: '余额',
            icon: <PayCircleOutlined />,
            value: 'Wallet'
          }
          break;
        case 'RemoteAlipay':
          obj = {
            title: '扫码支付（支付宝）',
            icon: <AlipayOutlined />,
            value: 'RemoteAlipay'
          }
          break;
        case 'RemoteWeChat':
          obj = {
            title: '扫码支付（微信）',
            icon: <WechatOutlined />,
            value: 'RemoteWeChat'
          }
          break;
      }
      return obj;
    })
    let orderId = data.orderId
    let payWay = data.payWay[0]
    this.setState({ collectionData, amountPrice: data.orderDueInyPrice, payWayData, orderId, payWay })
  }
  //三方支付dialog关闭
  thirdPartyDialogClose = () => {
    this.setState({ thirdPartyVisible: false, collectionVisible: true, thirdLoading: false })
  }
  continueToPay = async () => {
    let res = await apiStandOrderDetail({ orderId: this.state.orderId })
    if (res.data && res.code === 0) {
      this.initData(res.data)
      this.setState({ thirdPartyVisible: false })
    }
  }
  continueOrder = async (orderId) => {
    this.setState({
      collectionVisible: true,
      orderId
    })
    let res = await apiStandOrderDetail({ orderId })
    if (res.data && res.code === 0) {
      // this.print(res.data)
      this.initData(res.data)
      this.setState({ thirdPartyVisible: false })
    }
  }
  //结算dialog保存
  collectionDialogSave = () => {
    const { payWay } = this.state
    if (payWay === 'Cash') {
      this.setState({ cashVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
    if (payWay === 'Wallet') {
      this.setState({ walletVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
    if (payWay === 'Alipay') {
      this.setState({ aliPayVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
    if (payWay === 'WeChat') {
      this.setState({ weChatVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
    if (payWay === 'RemoteAlipay') {
      this.setState({ remoteAlipayVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
    if (payWay === 'RemoteWeChat') {
      this.setState({ remoteWeChatVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
    if (payWay === 'Other') {
      this.setState({ otherVisible: true, collectionVisible: false, cashPriceReason: '' })
    }
  }
  //取消收款
  collectionDialogReject = () => {
    const { orderId } = this.state
    if (orderId) {
      React.$confirm({
        title: '您确认取消该笔订单吗？',
        onOk: () => {
          this.setState({
            rejectVisible: true,
            discountFlag: 0,
            vcode: "",
            serviceDiscount: "",
            productDiscount: "",
            vuserId: "",
            discountRemark: "",
          })
        }
      })
    }
  }
  //结算方式切换
  payWayChange = (e) => {
    this.setState({ payWay: e.target.value })
  }
  print = (data) => {
    let token = sessionStorage.getItem('RSnetToken')
    React.$post('/management/storeInfo/storePrinterName').then(response => {
      const { receiptPrinterName } = response.data
      axios.post(`http://localhost:8888/admin/bill/print/${receiptPrinterName}`, { ...data }, {
        headers: {
          'Content-Type': 'application/json;charset=UTF-8',
          'RSnetToken': token,
          'Accept': '*/*'
        }
      })
    })
  }
  //现金结算dialog关闭
  cashDialogClose = () => {
    this.setState({ cashVisible: false, collectionVisible: true, cashPrice: 0, cashPriceReason: 0 })
  }
  //现金结算dailog保存
  cashDialogSave = () => {
    this.setState({
      cashVisible: false
    })
    this.payWaySettlement('cashVisible')

  }
  //现金结算备注
  payWayDescriptionChange = (e) => {
    this.setState({
      payWayDescription: e.target.value
    })
  }
  // 余额结算dialog关闭
  walleDialogClose = () => {
    this.setState({ walletVisible: false, collectionVisible: true, cashPrice: 0, cashPriceReason: 0 })

  }
  //余额结算dailog保存
  walletDialogSave = () => {
    this.setState({
      walletVisible: false
    })
    this.payWaySettlement('walletVisible')
  }
  //找零dialog保存
  settlementDialogSave = () => {
    this.setState({ settlementVisible: false, completionVisible: true }, () => this.continueToPay())
  }
  //找零dialog关闭
  settlementDialogClose = () => {
    this.setState({ settlementVisible: false, completionVisible: true }, () => this.continueToPay())
  }
  //输入收到现金金额
  cashChange = e => {
    this.setState({ cashPriceReason: e })
  }
  //完成结算关闭dialog还原变量
  DialogClose = () => {
    this.setState({
      completionVisible: false
    }, () => {
      this.getData()
    })
  }
  //其它结算dialog关闭
  otherDialogClose = () => {
    this.setState({ otherVisible: false, collectionVisible: true, cashPrice: 0, cashPriceReason: 0 })
  }
  //其它结算dailog保存
  otherDialogSave = () => {
    this.setState({
      otherVisible: false
    })
    this.payWaySettlement('otherVisible')
  }
  completionDialogClose = async () => {
    let { orderId, shoppingGuideId } = this.state
    this.setState({
      discountFlag: 0,
      vcode: "",
      serviceDiscount: "",
      productDiscount: "",
      vuserId: "",
      discountRemark: "",
    })
    // // let response = await apiStandOrderSettlement({ orderId, shoppingGuideId })
    // // if (response.code === 0) {
    let res = await apiGetStandOrderDetail({ orderId })
    if (res.data && res.code === 0) {
      this.print(res.data)
    }
    // this.props.history.push(`/cashier/cashier`)
    this.initState()
    this.getData()
    // // }
  }
  goToDetail = async () => {
    // if(this.state.serviceClassifyName === '酒店'){
    //     this.props.history.push(`/hotelOrder/list/${this.state.orderId}`)
    // }else{
    // let res = await apiStandOrderSettlement({ orderId: this.state.orderId, shoppingGuideId: this.state.shoppingGuideId })
    // if (res.code === 0) {
    this.props.history.push(`/cashier/order/details/${this.state.orderId}`)
    // }
    // }
  }
  //支付宝付款关闭
  alipayDialogClose = () => {
    this.setState({
      aliPayVisible: false,
      collectionVisible: true,
      scanCode: false
    })
  }
  alipayDialogSave = () => {
    const { cashPriceReason } = this.state
    if (!cashPriceReason) {
      return React.$message({
        type: 'info',
        content: '请输入金额'
      })
    }
    this.setState({
      aliPayVisible: false,
      thirdPartyVisible: true,
      scanCode: true
    })
  }
  //微信
  weChatDialogSave = () => {
    const { cashPriceReason } = this.state
    if (!cashPriceReason) {
      return React.$message({
        type: 'info',
        content: '请输入金额'
      })
    }
    this.setState({
      weChatVisible: false,
      thirdPartyVisible: true,
      scanCode: true
    })
  }
  weChatDialogClose = () => {
    this.setState({
      weChatVisible: false,
      collectionVisible: true,
      scanCode: false
    })
  }
  payWaySettlement = async (visible) => {
    const { payWay, orderId, cashPriceReason, payCode, payWayDescription, shoppingGuideId } = this.state
    console.log(this.state.payWayDescription)
    if (cashPriceReason === "" || cashPriceReason === null) {
      if (payWay == 'Wallet') {
        this.setState({
          walletVisible: true
        })
        return React.$message({
          type: 'info',
          content: '请输入金额'
        })
      }
      if (payWay == 'Cash') {
        this.setState({
          cashVisible: true
        })
        return React.$message({
          type: 'info',
          content: '请输入金额'
        })
      }
      if (payWay == 'Other') {
        this.setState({
          otherVisible: true
        })
        return React.$message({
          type: 'info',
          content: '请输入金额'
        })
      }
    }
    if (payWayDescription === "" || payWayDescription == null) {
      if (payWay == 'Other') {
        this.setState({
          otherVisible: true
        })
        return React.$message({
          type: 'info',
          content: '请输入备注'
        })
      }
    }
    let orderPayPrice = React.$transNum(cashPriceReason, 0, 2)
    let value = {}
    if (payWay === 'Cash' || payWay === 'Wallet') {
      value = {
        orderId,
        orderPayPrice,
        payWayDescription
      }
    } else if (payWay === 'RemoteAlipay') {
      value = {
        orderId,
        orderPayPrice: cashPriceReason,
        shoppingGuideId
      }
    } else if (payWay === 'RemoteWeChat') {
      value = {
        orderId,
        orderPayPrice: cashPriceReason,
        shoppingGuideId
      }
    } else if (payWay === 'Other') {
      value = {
        orderId,
        orderPayPrice,
        otherPayDescription: payWayDescription,
        shoppingGuideId
      }
    } else {
      value = {
        orderId,
        orderPayPrice,
        payCode
      }
    }
    this.setState({ thirdLoading: true }, () => {
      React.$post(`/management/order/standOrderPay/${payWay}`, { ...value }).then(res => {
        if (res.data && res.code === 0) {
          if (payWay === 'RemoteAlipay') {
            this.setState({
              __html: res.data.url,
              remoteAlipayResultVisible: true,
              thirdLoading: false, cashPriceReason: "", payWay,
            }, () => {
            })
            return false;
          }
          if (payWay === 'RemoteWeChat') {
            this.setState({
              remoteWeChatQrCodeStr: res.data.url,
              remoteWeChatResultVisible: true,
              thirdLoading: false, cashPriceReason: "", payWay,
            }, () => {
              this.pollingPayResult(orderId)
            })
            return false;
          }
          const { status } = res.data
          console.log(status);
          if (status === false) {
            this.continueToPay()
            this.setState({ [visible]: false, collectionVisible: true, payWayDescription: "" })
          } else if (status === true) {
            const { amount } = res.data
            if (amount > 0) {
              this.setState({ [visible]: false, settlementVisible: true, differencePrice: amount, cashPrice: cashPriceReason, payWayDescription: "" })
            } else {
              this.continueToPay()
              this.setState({ completionVisible: true, [visible]: false, payWayDescription: "" })
            }
          }
          this.setState({ thirdLoading: false, cashPriceReason: "", payWay, scanCode: false })
        } else {
          this.setState({
            thirdLoading: false, cashPriceReason: "", payWay,
            thirdPartyVisible: false, collectionVisible: true, scanCode: false, payWayDescription: ""
          })
        }
      }).catch(err => {
        React.$message({
          type: 'error',
          content: '支付超时，请重新支付'
        })
        this.setState({ thirdLoading: false, cashPriceReason: "", payWay, thirdPartyVisible: false, collectionVisible: true, scanCode: false, payWayDescription: "" })
      })
    })

  }
  pollingPayResult = async (orderId) => {
    if (!this.state.remoteWeChatResultVisible) return
    const res = await apiOrderPollingPayResult({ orderId })
    if (res.code == 0) {
      const { status } = res.data
      if (status == 'success') {
        this.setState({
          orderId,
          completionVisible: true,
          remoteWeChatResultVisible: false
        }, () => {
          this.continueToPay()
        })
      } else if (status == 'invalid') {
        React.$message({
          type: 'warning',
          content: '二维码失效！'
        })
      } else if (status == 'paying') {
        setTimeout(() => {
          this.pollingPayResult(orderId)
        }, 2000)
      }
    }

  }
  selectChange = (shoppingGuideId) => {
    this.setState({
      shoppingGuideId
    })
  }
  rejectDialogSave = async () => {
    const { orderId, cancelRemark } = this.state
    this.setState({ rejectLoading: true })
    let res = await apiStandOrderCancel({ orderId, remark: cancelRemark })
    if (res.code === 0) {
      this.initState()
    } else {
      this.setState({ rejectLoading: false, rejectVisible: false }, () => {
        React.$message({
          type: 'info',
          content: '取消失败'
        })
      })
    }
  }
  initState = () => {
    let state = {
      tabsServiceData: [],
      tabsCommodityData: [],
      radioOption: [
        {
          title: '服务列表',
          value: 'service'
        },
        {
          title: '商品列表',
          value: 'commodity'
        },
      ],
      buttonValue: 'service',
      serviceData: [],
      commodityData: [],
      serviceSelectData: [],
      commoditySelectData: [],
      priceId: '',
      totalCount: 0,
      totalPrice: 0,
      totalIntegral: 0,
      discountPrice: 0,
      discountReason: '',
      discountVisible: false,
      memberVisible: false,
      memberMobile: '',
      memberData: {},
      collectionData: [],
      payWayData: [],
      payWay: 'Cash',
      servicePageNo: 1,
      commodityPageNo: 1,
      serviceTotal: 0,
      commodityTotal: 0,
      storeServiceName: '',
      productNameOrCode: '',
      serviceSearchValue: '',
      commoditySearchValue: '',
      thirdLoading: false,
      rejectLoading: false,
      serviceClassifyId: '',
      productClassifyId: '',
      rejectVisible: false,
      collectionVisible: false,
      orderId: '',
      showIndex: '',
      completionVisible: false,
      cancelRemark: '订单异常关闭',
      shoppingGuideId: '',
      scanCode: false,
      couponDiscountTotal: '',
      productMaxOutPrice: ''
    }
    this.setState({ ...state }, () => {
      this.componentDidMount()
    })
  }
  getPayWay = (value) => {
    let str = ''
    switch (value) {
      case 'Hybrid':
        str = '混合支付'
        break
      case 'Alipay':
        str = '支付宝'
        break
      case 'WeChat':
        str = '微信'
        break
      case 'Cash':
        str = '现金'
        break
      case 'Wallet':
        str = '余额'
        break
      case 'Other':
        str = '其他支付'
        break
      case 'RemoteAlipay':
        str = '扫码支付（支付宝）'
        break
      case 'RemoteWeChat':
        str = '扫码支付（微信）'
        break
      default:
        str = '混合支付'
        break
    }
    return str;
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  getValue = value => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => this.getData())
  }
  openDialog = async (orderId) => {
    let res = await apiGetStandOrderDetail({ orderId })
    if (res.data && res.code === 0) {
      let data = res.data
      let checked = false
      if (data.couponDiscountTotal !== null && data.couponDiscountTotal > 0) {
        checked = true
        let chargebackCommodityData = data.standProductList.map(v => {
          let productJson = JSON.parse(v.productSkuJson)
          let { skuAttribute } = productJson
          let sku = skuAttribute.map(k => k.product_value)
          return {
            ...v,
            sku,
            returnCount: 0,
            checked,
            display: true,
          }
        })
        let chargebackServiceData = data.standServiceList.map((v, i) => {
          return {
            ...v,
            index: i,
            checked,
            display: true
          }
        })
        let chargebackOtherData = data.standOtherList.map(v => {
          return {
            ...v,
            checked,
            display: true
          }
        })
        let orderId = data.orderId
        this.setState({
          visible: true,
          chargebackCommodityData,
          chargebackServiceData,
          chargebackOtherData,
          orderId,
          couponDiscountTotal: data.couponDiscountTotal,
          productMaxOutPrice: data.productMaxOutPrice
        }, () => {
          this.handleCombined()
        })
      } else if(data.productMaxOutPrice && data.productMaxOutPrice > 0) {
        checked = true
        let chargebackCommodityData = data.standProductList.map(v => {
          let productJson = JSON.parse(v.productSkuJson)
          let { skuAttribute } = productJson
          let sku = skuAttribute.map(k => k.product_value)
          return {
            ...v,
            sku,
            returnCount: 0,
            checked,
            display: true,
          }
        })
        let chargebackServiceData = data.standServiceList.map((v, i) => {
          return {
            ...v,
            index: i,
            checked,
            display: true
          }
        })
        let chargebackOtherData = data.standOtherList.map(v => {
          return {
            ...v,
            checked,
            display: true
          }
        })
        let orderId = data.orderId
        this.setState({
          visible: true,
          chargebackCommodityData,
          chargebackServiceData,
          chargebackOtherData,
          orderId,
          couponDiscountTotal: data.couponDiscountTotal,
          productMaxOutPrice: data.productMaxOutPrice
        }, () => {
          console.log(this.state.chargebackCommodityData);
          this.handleCombined()
        })
      }else {

        let chargebackCommodityData = data.standProductList.map(v => {
          let productJson = JSON.parse(v.productSkuJson)
          let { skuAttribute } = productJson
          let sku = skuAttribute.map(k => k.product_value)
          return {
            ...v,
            sku,
            returnCount: 0,
            checked,
            display: false
          }
        })
        let chargebackServiceData = data.standServiceList.map((v, i) => {
          return {
            ...v,
            index: i,
            checked,
            display: false
          }
        })
        let chargebackOtherData = data.standOtherList.map(v => {
          return {
            ...v,
            checked,
            display: false
          }
        })
        let orderId = data.orderId
        this.setState({
          visible: true,
          chargebackCommodityData,
          chargebackServiceData,
          chargebackOtherData,
          orderId,
          couponDiscountTotal: data.couponDiscountTotal,
          productMaxOutPrice: data.productMaxOutPrice
        })
      }
    }

  }
  countChange = (type, value, from, e, ref) => {
    if (type === 'commodity') {
      let { chargebackCommodityData } = this.state
      let arr = []
      if (from === 'reduce') {
        arr = chargebackCommodityData.map(v => {
          if (v.orderDetailId === value.orderDetailId) {
            if (_.toNumber(v.returnCount) === 0) {
              return v
            } else {
              return {
                ...v,
                returnCount: _.toNumber(v.returnCount) - 1
              }
            }
          } else {
            return v
          }
        })
      }
      if (from === 'add') {
        arr = chargebackCommodityData.map(v => {
          if (v.orderDetailId === value.orderDetailId) {
            if (_.toNumber(v.returnCount) === _.toNumber(v.orderProductCount)) {
              return v
            } else {
              return {
                ...v,
                returnCount: _.toNumber(v.returnCount) + 1
              }
            }
          } else {
            return v
          }
        })
      }
      if (from === 'input') {
        arr = chargebackCommodityData.map(v => {
          if (v.orderDetailId === value.orderDetailId) {
            if (_.toNumber(e) > _.toNumber(v.orderProductCount)) {
              return {
                ...v,
                returnCount: _.toNumber(v.orderProductCount)
              }
            } else if (_.toNumber(e) < 0) {
              return {
                ...v,
                returnCount: 0
              }
            } else {
              return {
                ...v,
                returnCount: _.toNumber(e)
              }
            }
          } else {
            return v
          }
        })
        this[ref].blur()
      }
      this.setState({ chargebackCommodityData: arr }, () => this.handleCombined())
    }
  }
  handleCombined = async () => {
    let params = this.getReturnData()
    console.log(params);
    let res = await apiStandSalesReturn({ ...params })
    if (res.data && res.code === 0) {
      let data = res.data
      let totalReturnCount = data.totalItems
      let totalReturnPrice = data.salesAmount
      let totalReturnIntegral = data.salesScore
      this.setState({
        totalReturnCount,
        totalReturnPrice,
        totalReturnIntegral
      })
    }
  }
  dialogClose = () => {
    this.setState({
      visible: false,
      totalReturnCount: 0,
      totalReturnPrice: 0,
      totalReturnIntegral: 0,
      chargebackCommodityData: [],
      chargebackServiceData: []
    })
  }
  priceDialogOpen = () => {
    const { chargebackCommodityData, chargebackServiceData } = this.state
    if (!this.state.totalReturnPrice) {
      return React.$message({
        type: 'info',
        content: '请选择退款的商品或服务项目'
      })
    } else {
      this.setState({
        priceVisible: true,
        visible: false
      })
    }
  }
  changeChecked = (value, type) => {
    const { chargebackServiceData, chargebackCommodityData } = this.state
    if (type === 'service') {
      let arr = JSON.parse(JSON.stringify(chargebackServiceData))
      arr = arr.map(v => {
        if (v.index === value.index) {
          return {
            ...v,
            checked: !v.checked
          }
        } else {
          return v
        }
      })
      this.setState({ chargebackServiceData: arr }, () => this.handleCombined())
    } else if (type === 'commodity') {
      let arr2 = chargebackCommodityData.map(v => {
        console.log(v, '======', value);
        if (v.orderDetailId === value.orderDetailId) {
          return {
            ...v,
            checked: !v.checked
          }
        } else {
          return v
        }
      })
      this.setState({ chargebackCommodityData: arr2 }, () => this.handleCombined())

    }

  }
  deductionChange = value => {
    const { chargebackOtherData } = this.state
    this.setState({
      chargebackOtherData: chargebackOtherData.map(v => {
        if (v.orderDetailId === value.orderDetailId) {
          return {
            ...v,
            checked: !v.checked
          }
        } else {
          return v
        }
      })
    }, () => this.handleCombined())
  }
  getReturnData = () => {
    const { chargebackCommodityData, chargebackServiceData, chargebackOtherData, orderId } = this.state
    let orderDetails = []
    let productList = chargebackCommodityData.filter(v => v.checked).map(k => {
      console.log(k);

      orderDetails.push(k.orderDetailId)
      return {
        count: k.orderProductCount,
        orderDetailId: k.orderDetailId
      }
    })
    let storeServiceList = chargebackServiceData.filter(v => v.checked).map(k => {
      console.log(k);
      orderDetails.push(k.orderDetailId)
      return {
        orderDetailId: k.orderDetailId
      }
    })
    let otherServiceList = chargebackOtherData.filter(v => v.checked).map(k => {
      console.log(k);

      orderDetails.push(k.orderDetailId)
      return {
        orderDetailId: k.orderDetailId
      }
    })
    return {
      orderId,
      orderDetails,
      productList,
      storeServiceList,
      otherServiceList
    }
  }
  dialogSave = async () => {
    let params = this.getReturnData()
    let { orderDetails, orderId } = params
    if (!orderDetails || orderDetails.length <= 0) {
      return React.$message({
        type: 'warning',
        content: '请选择退款的商品或服务项目'
      })
    }
    React.$confirm({
      title: '您确认退款吗？',
      onOk: async () => {
        let res = await apiStandSalesReturnOrder({ orderDetails, orderId })
        if (res.data && res.code === 0) {
          this.setState({
            returnVisible: true,
            visible: false,
            returnData: res.data,
            standSalesReturnId: res.data.standSalesReturnId
          })
        }
      }
    })
  }
  returnDialogClose = () => {
    this.setState({
      returnVisible: false,
      returnData: []
    }, () => this.getData())
  }
  async exportTable(option) {
    // return React.$message({
    //   type: 'warning',
    //   content: '暂未开放'
    // })
    this.setState({
      exportLoading: true
    })
    let tH_data = [{ prop: 'orderCode', title: '订单编号' }, { prop: 'orderMemberName', title: '用户昵称' },
    { prop: 'orderPayPrice', title: '实收金额', valueType: 'number' }, { prop: 'payWay', title: '付款方式' },
    { prop: 'presentIntegral', title: '赠送积分', valueType: 'number' }, { prop: 'cashierName', title: '收款人员' },
    { prop: 'shoppingGuideName', title: '导购人员' }, { prop: 'createTime', title: '付款时间' }]

    let res = await apiGetStandOrderPage({ pageNo: 1, pageSize: 9999, createTimeEnd: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[1]) : '', createTimeStart: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[0]) : '', orderCode: (option.hasOwnProperty('orderCode') && option.orderCode) ? option.orderCode : '', orderState: 9 })
    if (res.code === 0) {
      let tB_data = res.data.map(item => {
        return {
          ...item,
          payWay: this.getPayWay(item.payWay),
          orderPayPrice: Number(item.orderPayPrice / 100).toFixed(2)
        }
      }),
        fileName = '订单列表(线下门店)',
        isSheet = true
      exportSheetTable({ fileName, tH_data, tB_data, isSheet })
      this.setState({
        exportLoading: false
      })
    }
  }
  async exportSaleOutTable(option) {
    let res = await apiExportLibraryOutReport({
      createTimeEnd: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[1]) : '', createTimeStart: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[0]) : '', orderCode: (option.hasOwnProperty('orderCode') && option.orderCode) ? option.orderCode : ''
    })
    if (res.code === 0 && res.data) {
      const th_arr = [
        {
          title: '序号',
          prop: 'productId'
        },
        {
          title: '日期',
          prop: 'day'
        },
        {
          title: '物料Id',
          prop: 'materialId',
        },
        {
          title: '库存单位',
          prop: 'unit'
        },
        {
          title: '实发数量',
          prop: 'orderProductCount', valueType: 'number'
        },
        {
          title: '含税单价',
          prop: 'orderPrice', valueType: 'number'
        }
      ]
      const tb_arr = res.data
      exportSheetTable({ fileName: '销售出库单(线下门店)', tH_data: th_arr, tB_data: tb_arr, isSheet: true })

    }

  }
  async exportOrder(option) {
    this.setState({
      exportLoading: true
    })
    let now = moment(new Date().getTime()).format("YYYY-MM-DD");
    let MonthDate = new Date();
    MonthDate.setDate(1); //set设置时间
    MonthDate.setHours(0);
    MonthDate.setSeconds(0);
    MonthDate.setMinutes(0);
    let nowMonth = moment(MonthDate.getTime()).format("YYYY-MM-DD")
    let res = await apiGetOrderExportOrder({
      createTimeEnd: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[1]) : now, createTimeStart: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[0]) : nowMonth, orderCode: (option.hasOwnProperty('orderCode') && option.orderCode) ? option.orderCode : ''
    })
    if (res.code === 0) {
      let tH_data = [
        {
          title: '资金日报订单',
          prop: '',
          children: [
            {
              title: '序号',
              prop: 'index',
              merge: true
            },
            {
              title: '订单编号',
              prop: 'orderCode',
              merge: true
            },
            {
              title: '用户昵称',
              prop: 'orderMemberName',
              merge: true
            },
            {
              title: '物料ID',
              prop: 'materialId'
            },
            {
              title: '商品名称',
              prop: 'productName',

            },
            {
              title: '规格',
              prop: 'sku',

            },
            {
              title: '商品价格',
              prop: 'orderPriceTotal',
              valueType: 'n'

            },
            {
              title: '商品折扣',
              prop: 'discount',

            },

            {
              title: '商品数量',
              prop: 'orderProductCount',
              valueType: 'n'
            },
            {
              title: '收入类型',
              prop: 'type',

            },

            {
              title: '付款方式',
              prop: 'payWay',
              merge: true
            },
            {
              title: '计算方式',
              prop: '',
              children: res.data.payWay.map(item => {
                return {
                  title: item.name,
                  prop: item.value,
                  valueType: 'n',
                  merge: true
                }
              })
            },
            {
              title: '其他收款备注',
              prop: 'depositCardNumber',
              merge: true
            },
            {
              title: '应付金额',
              prop: 'orderTotalPrice', valueType: 'n',
              merge: true
            },
            {
              title: '优惠金额',
              prop: 'couponTotal', valueType: 'n',
              merge: true

            },
            {
              title: '满件优惠金额',
              prop: 'productMaxOutPrice', valueType: 'n',
              merge: true
            },
            {
              title: '退款',
              prop: 'refundPrice', valueType: 'n',
              merge: true
            },
            {
              title: "退款时间",
              prop: 'refundTime',
              merge: true
            },
            {
              title: '实收金额',
              prop: 'realityPayPrice', valueType: 'n',
              merge: true
            },
            {
              title: '赠送积分',
              prop: 'presentIntegral',
              merge: true
            },
            {
              title: '收款人员',
              prop: 'cashierName',
              merge: true
            },
            {
              title: '导购人员',
              prop: 'shoppingGuideName',
              merge: true
            },
            {
              title: '付款时间',
              prop: 'createTime',
              merge: true
            },
          ]
        },

      ]
      this.setState({
        exportLoading: false
      })
      let tB_data = []
      res.data.exportOrderVos.forEach(item => {
        item.orderDetails.forEach(item2 => {
          tB_data.push({
            index: item.index,
            orderCode: item.orderCode || '/',
            orderMemberName: item.orderMemberName || '/',
            materialId: item2.materialId || '/',
            productName: item2.productName || '/',
            sku: item2.sku || '/',
            orderPriceTotal: Number(item2.orderPriceTotal).toFixed(2) || '/',
            discount: Number(item2.discount).toFixed(2) + "%" || '/',
            orderProductCount: item2.orderProductCount || '/',
            type: item2.type || '/',
            depositCardNumber: item.depositCardNumber || '/',
            payWay: item.payWay || '/',
            Alipay: Number(item.payWayMap.Alipay) || '0',
            Cash: Number(item.payWayMap.Cash) || '0',
            Other: Number(item.payWayMap.Other) || '0',
            Pos: Number(item.payWayMap.Pos) || '0',
            Wallet: Number(item.payWayMap.Wallet) || '0',
            WeChat: Number(item.payWayMap.WeChat) || '0',
            orderTotalPrice: Number(item.orderTotalPrice).toFixed(2) || '/',
            couponTotal: Number(item.couponTotal).toFixed(2) || '/',
            productMaxOutPrice: Number(item2.productMaxOutPrice).toFixed(2) || '0',
            refundPrice: Number(item.refundPrice).toFixed(2) || '0',
            refundTime: item.refundTime || "/",
            realityPayPrice: Number(item.realityPayPrice).toFixed(2) || '0',
            presentIntegral: item.presentIntegral || '0',
            cashierName: item.cashierName || '/',
            shoppingGuideName: item.hasOwnProperty('shoppingGuideName') ? item.shoppingGuideName : '/',
            createTime: item.createTime || '/'
          })
        })
      })
      const mergeProp = [
        {
          key: 'depositCardNumber'
        },
        {
          key: 'Other'
        },
        {
          key: 'index'
        }, {
          key: 'couponTotal'
        }, {
          key: 'orderCode'
        }, {
          key: 'realityPayPrice'
        }, {
          key: 'orderTotalPrice'
        }, {
          key: 'orderMemberName'
        }, {
          key: 'payWay'
        }, {
          key: 'back',
          // reg: /^\s*$/g
        }, {
          key: 'count'
        }, {
          key: 'presentIntegral'
        }, {
          key: 'cashierName'
        }, {
          key: 'refundPrice'
        }, {
          key: 'shoppingGuideName'
        }, {
          key: 'createTime'
        }, {
          key: 'Alipay',
          // reg: /\/{0}/g
        }, {
          key: 'Cash'
        }, {
          key: 'Pos'
        }, {
          key: 'Wallet'
        }, {
          key: 'WeChat'
        }, {
          key: 'refundTime'
        }, {
          key: 'productMaxOutPrice'
        }
      ]
      Json2Excel({ header: tH_data, dataSource: tB_data, fileName: '资金日报订单(线下门店)' })
    }
  }
  async exportDayTable(option) {
    console.log(option === true);
    // return React.$message({
    //   type: 'warning',
    //   content: '暂未开放'
    // })

    this.setState({
      exportLoading: true
    })

    let res = await apiOrderExportCapitalDaily({
      createTimeEnd: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[1]) : '', createTimeStart: (option.hasOwnProperty('time') && option.time.length > 0) ? getDateTime3(option.time[0]) : '', orderCode: (option.hasOwnProperty('orderCode') && option.orderCode) ? option.orderCode : ''
    })

    if (res.code === 0) {
      this.setState({
        exportTableData: res.data.data.map(item => {
          return {
            ...item,
            paywayPrice: Number(item.paywayPrice).toFixed(2),
            service: Number(item.service).toFixed(2),
            goods: Number(item.goods).toFixed(2),
            otherService: Number(item.otherService).toFixed(2),
            count: Number(item.count).toFixed(2),
            vip: Number(item.vip).toFixed(2),
            back: Number(item.back).toFixed(2),

          }
        }),
        exportTablePay_way: res.data.pay_way
      }, () => {

        let tH_data = [
          {
            title: '日期',
            prop: 'day'
          },
          {
            title: '计算方式',
            prop: '',
            children: this.state.exportTablePay_way.map(item => {
              return {
                title: item.name,
                prop: item.value,
                valueType: 'number'
              }
            })
          },
          {
            title: '服务收入',
            prop: 'service', valueType: 'number'
          },
          {
            title: '商品收入',
            prop: 'goods', valueType: 'number'
          },
          {
            title: '其他服务',
            prop: 'otherService', valueType: 'number'
          },
          {
            title: '会员卡收入',
            prop: 'vip', valueType: 'number'
          },
          {
            title: '退款',
            prop: 'back', valueType: 'number'
          },
          {
            title: '总收入',
            prop: 'count', valueType: 'number'
          },
        ]
        tH_data[1].children.push({
          title: "小计",
          prop: "paywayPrice", valueType: 'number'
        })
        this.setState({
          exportLoading: false
        })

        exportSheetTable({ tH_data, tB_data: this.state.exportTableData, fileName: '资金日报(线下门店)', isSheet: true })

      })
    }
  }
  goToDetail = async () => {

    this.props.history.push(`/cashier/order/details/${this.state.orderId}`)

  }
  // 扫码支付（支付宝）关闭
  remoteAlipayDialogClose = () => {
    this.setState({ remoteAlipayVisible: false, collectionVisible: true, cashPrice: 0, cashPriceReason: 0 })
  }
  // 扫码支付（支付宝）保存
  remoteAlipayDialogSave = () => {
    this.setState({
      remoteAlipayVisible: false,
      cashPriceReason: this.state.amountPrice
    }, () => this.payWaySettlement('remoteAlipayVisible'))
  }
  //支付宝扫码支付dialog关闭
  remoteAlipayResultDialogClose = () => {
    this.setState({ remoteAlipayResultVisible: false, collectionVisible: true, thirdLoading: false, scanCode: false })
  }
  //支付宝扫码支付dialog确认收款

  remoteAlipayResultDialogSave = () => {
    const punchout_form = document.querySelector('form[name="punchout_form"]')
    punchout_form.submit()
  }


  // 扫码支付（支付宝）关闭
  remoteWeChatDialogClose = () => {
    this.setState({ remoteWeChatVisible: false, collectionVisible: true, cashPrice: 0, cashPriceReason: 0 })
  }
  // 扫码支付（支付宝）保存
  remoteWeChatDialogSave = () => {
    this.setState({
      remoteWeChatVisible: false,
      cashPriceReason: this.state.amountPrice
    }, () => this.payWaySettlement('remoteWeChatVisible'))
  }
  //支付宝扫码支付dialog关闭
  remoteWeChatResultDialogClose = () => {
    this.setState({ remoteWeChatResultVisible: false, collectionVisible: true, thirdLoading: false, scanCode: false })
  }
  //支付宝扫码支付dialog确认收款

  remoteWeChatResultDialogSave = () => {

  }

  cancelCharge = () => {
    this.setState({
      collectionVisible: false
    })
  }
  render() {
    const { otherVisible, columns, dataSource, remoteAlipayResultVisible, remoteWeChatQrCodeStr, __html, remoteAlipayVisible, remoteWeChatResultVisible, remoteWeChatVisible, exportTablePay_way, exportTableData, loading, exportLoading, pageData: { pageSize, pageNo }, total, visible, chargebackCommodityData, chargebackServiceData, totalReturnCount, totalReturnPrice, totalReturnIntegral, standSalesReturnId, chargebackOtherData, returnVisible, returnData, orderState, collectionVisible, collectionData, slaesmanData, shoppingGuideId, payWayData, payWay, amountPrice, cashVisible, cashPriceReason, payWayDescription, aliPayVisible, weChatVisible, settlementVisible, cashPrice, differencePrice, completionVisible, thirdPartyVisible, thirdLoading, rejectVisible, rejectLoading, walletVisible, couponDiscountTotal, productMaxOutPrice } = this.state
    return (
      <div className='p-layout-box'>
        <table id='exportTableModal' border={1} cellSpacing={0} cellPadding={10} width={1000} style={{
          textAlign: 'center', position: 'fixed',
          left: '111110px',
          top: '111110px',
        }}>
          <thead>
            <tr style={{ textAlign: 'center' }}>
              <td style={{ textAlign: 'center' }} colSpan={exportTablePay_way.length + 6} rowSpan={1}>资金日报</td>
            </tr>
            <tr style={{ textAlign: 'center' }}>
              <td colSpan={1} rowSpan={2}>日期</td>
              <td colSpan={exportTablePay_way.length} rowSpan={1}> 计算方式</td>
              <td colSpan={1} rowSpan={2}>服务收入</td>
              <td colSpan={1} rowSpan={2}>商品收入</td>
              <td colSpan={1} rowSpan={2}>其他服务</td>
              <td colSpan={1} rowSpan={2}>退款</td>
              <td colSpan={1} rowSpan={2}>总收入</td>
            </tr>
            <tr style={{ textAlign: 'center' }}>
              {
                exportTablePay_way.map(item => {
                  return (<td>{item.name}</td>)
                })
              }
            </tr>
          </thead>
          {
            exportTableData.length > 0 ? <tbody>
              {
                exportTableData.map(item => {
                  return (
                    <tr style={{ textAlign: 'center' }}>
                      <td>{item.day}</td>
                      {
                        exportTablePay_way.map(td => {
                          return (<td>{item[td.value]}</td>)
                        })
                      }
                      <td>{item.service}</td>
                      <td>{item.goods}</td>
                      <td>{item.otherService}</td>
                      <td>{item.back}</td>
                      <td>{item.count}</td>
                    </tr>
                  )
                })
              }
            </tbody> : <tbody></tbody>
          }

        </table>
        {/* <SearchHeader getValue={this.getValue} exportLoading={exportLoading} orderState={orderState} exportExcel={(e) => this.exportTable(e)} exportOrder={(e) => this.exportOrder(e)} exportSaleOutTable={(e) => this.exportSaleOutTable(e)} exportDay={(e) => this.exportDayTable(e)} /> */}
        <div className="p-layout-content-pagination">
          <Tabs activeKey={orderState} onChange={this.changeKey}
            tabBarExtraContent={
              <SearchHeader getValue={this.getValue} exportLoading={exportLoading} orderState={orderState} exportExcel={(e) => this.exportTable(e)} exportOrder={(e) => this.exportOrder(e)} exportSaleOutTable={(e) => this.exportSaleOutTable(e)} exportDay={(e) => this.exportDayTable(e)} />
            }
          >
            <TabPane key={"9"} tab={"已完成"}  >
              <TheTable columns={columns} dataSource={dataSource} loading={loading} scroll={{ x: "max-content", y: '60vh' }} />
              <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
            </TabPane>
            <TabPane key={"1"} tab={"未完成"}  >
              <TheTable columns={columns} dataSource={dataSource} loading={loading} scroll={{ x: "max-content", y: '60vh' }} />
              <ThePagination pageNo={pageNo} pageSize={pageSize} total={total} pageChange={this.pageChange} />
            </TabPane>
          </Tabs>

        </div>
        <CashierModal
          visible={visible}
          title="选择退款商品"
          width={1000}
          onCancel={this.dialogClose}
          footer={
            <div className='cashier-order-dialog-footer'>
              <div className='total'>
                <p>共选择<span>{totalReturnCount}</span>项，实退金额：<React.$Price price={totalReturnPrice} />&nbsp;&nbsp;扣除积分：{_.toNumber(totalReturnIntegral).toLocaleString()}</p>
                {couponDiscountTotal || productMaxOutPrice ? <p style={{ color: "red" }}>该账单有优惠券或满件优惠，如需退单个商品，则需全部退款，再生成正确订单</p> : null}
              </div>
              <div className='button-group'>
                <div onClick={this.dialogClose} className='button cancel'>取 消</div>
                <div onClick={this.dialogSave} className='button submit'>{couponDiscountTotal || productMaxOutPrice ? "全部退款" : "退 款"}</div>
              </div>
            </div>
          }
        >
          <div className='cashier-order-dialog-box'>
            {!_.isEmpty(chargebackServiceData) && <div className='content'>
              <div className='title'>服务项</div>
              <div className='cintainer'>
                {
                  chargebackServiceData.map((v, i) => {
                    return <div className='item' key={i}>
                      <div className='top'>
                        <div>{v.productName}</div>
                        <div className='total'>价格：{<React.$Price price={v.orderPrice} color="#EF3800" />}</div>
                      </div>
                      <div className='bottom'>
                        {
                          !v.display && v.checked && <div onClick={() => this.changeChecked(v, 'service')} className='chargeback-button-active'>取消退款</div>
                        }
                        {
                          !v.checked && <div onClick={() => this.changeChecked(v, 'service')} className='chargeback-button'>选择退款</div>
                        }
                      </div>
                    </div>
                  })
                }
              </div>
            </div>}
            {!_.isEmpty(chargebackCommodityData) && <div className='content'>
              <div className='title'>商品项</div>
              <div className='cintainer'>
                {
                  chargebackCommodityData.map((v, i) => {
                    return <div className='item'>
                      <div className='top'>
                        <div>
                          <div>{v.productName}</div>
                          <div className='sku'>{v.sku}</div>
                        </div>
                        <div>商品单价：{<React.$Price price={v.orderPrice} color="#222" />}</div>
                        <div>商品数量：{v.orderProductCount}</div>
                        <div className='total'>
                          合计：
                          {<React.$Price price={v.orderPriceTotal - v.productMaxOutPrice} color="#EF3800" />}
                        </div>
                      </div>
                      <div className='bottom'>
                        {
                          !v.display && v.checked && <div onClick={() => this.changeChecked(v, 'commodity')} className='chargeback-button-active'>取消退款</div>
                        }
                        {
                          !v.checked && <div onClick={() => this.changeChecked(v, 'commodity')} className='chargeback-button'>选择退款</div>
                        }
                      </div>
                      {/* <div className='bottom'>
                        <span>退款数量：</span>
                        <div style={{ display: 'flex' }}>
                          <TheImage
                            onClick={() => this.countChange('commodity', v, 'reduce')}
                            preview={false}
                            src={reduce}
                            width={22}
                            height={22} />

                          <InputNumber
                            ref={ref => this[`countRefCommodity${i}`] = ref}
                            min={0}
                            max={v.orderProductCount}
                            precision={0}
                            onPressEnter={(e) =>
                              this.countChange('commodity', v, 'input', e.target.value, `countRefCommodity${i}`)}
                            style={{ width: 50, margin: '0 10px' }}
                            value={v.returnCount} />

                          <TheImage
                            onClick={() => this.countChange('commodity', v, 'add')}
                            preview={false}
                            src={increase}
                            width={22}
                            height={22} />
                        </div>
                      </div> */}
                    </div>
                  })
                }
              </div>
            </div>}
            {!_.isEmpty(chargebackOtherData) && <div className='content'>
              <div className='title'>其他项</div>
              <div className='cintainer'>
                {chargebackOtherData.map(v => {
                  return <div className='item'>
                    <div className='top'>
                      <div>
                        <div>其他服务</div>
                        <div className='sku'>{v.orderProductRemark}</div>
                      </div>
                      <div className='total'>价格：
                        {<React.$Price price={v.orderPrice} color="#EF3800" />}
                      </div>
                    </div>
                    <div className='bottom'>
                      {
                        !v.display && v.checked && <div onClick={() => this.deductionChange(v)} className='chargeback-button-active'>取消退款</div>
                      }
                      {
                        !v.checked && <div onClick={() => this.deductionChange(v)} className='chargeback-button'>选择退款</div>
                      }
                    </div>
                  </div>
                })}
              </div>
            </div>}
          </div>
        </CashierModal>
        <CashierModal
          title="其他"
          visible={otherVisible}
          onCancel={this.otherDialogClose}
          onOk={this.otherDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>
          <InputNumber
            min={0}
            max={1000000}
            precision={2}
            placeholder="请输入收款金额"
            onChange={this.cashChange}
            ref={ref => this.cashInputRef = ref}
            value={cashPriceReason}
            style={{ marginBottom: "10px" }}
          />
          <Input
            allowClear
            maxLength={200}
            placeholder='请输入请备注'
            value={payWayDescription}
            ref={ref => this.payWayDescriptionRef = ref}
            onChange={this.payWayDescriptionChange} />
        </CashierModal>
        <CashierModal
          title="退款方式"
          visible={returnVisible}
          width={600}
          onCancel={this.returnDialogClose}
          footer={
            <div className='completion-button-group'>
              <div onClick={() => this.props.history.push(`/cashier/chargeback/details/${standSalesReturnId}`)} className='dialog-footer-button' style={{ width: 200 }}>
                <div>查看退款单</div>
              </div>
              <div style={{ width: 200 }} onClick={this.returnDialogClose} className='dialog-footer-button'>
                <div>确认</div>
              </div>
            </div>
          }
        >
          <div className='finish-box'>
            <TheImage src={finish} width={256} height={188} preview={false} />
            <div>退款成功</div>
            <div>通过账单可查看详情</div>
          </div>
          <div className='collection-box'>
            <div className='collection-information'>
              <div className='collection-title'>退款明细</div>
              <div className="collection-information-content">
                <div className='collection-information-content-item'>
                  <div>实退金额</div>
                  <div>
                    <React.$Price price={returnData.salesAmount} />
                  </div>
                </div>
                <div className='collection-information-content-item'>
                  <div>扣除积分</div>
                  <div >
                    {_.toNumber(returnData.salesScore).toLocaleString()}
                  </div>
                </div>
              </div>
            </div>
            <div className='collection-information'>
              <div className='collection-title'>退款方式</div>
              <div className="collection-information-content">
                {
                  _.map(returnData.payData, (v, k) => {
                    return <div className='collection-information-content-item'>
                      <div>{k}</div>
                      <div>
                        <React.$Price price={v} color={k.includes('现金') ? '#EF3800' : '#000'} />
                      </div>
                    </div>
                  })
                }
              </div>
            </div>
          </div>
        </CashierModal>
        <CashierModal
          title="收款结算"
          visible={collectionVisible}
          onCancel={this.cancelCharge}
          width={1500}
          footer={
            <div className='completion-button-group'>
              <div onClick={this.collectionDialogReject} className='dialog-footer-button'>
                <div>取消收款</div>
              </div>
              <div onClick={this.collectionDialogSave} className='dialog-footer-button'>
                <div>确认收款</div>
              </div>
            </div>
          }
        >
          <div className='collection-box'>
            <div className='collection-information'>
              <div className='collection-title'>费用结算</div>
              <div className="collection-information-content">
                {
                  collectionData.map(v => {
                    return <div className='collection-information-content-item'>
                      <div>{v.title}</div>
                      <div>{v.value}</div>
                    </div>
                  })
                }
              </div>
            </div>
            <div className='collection-pay-way'>
              <div className='collection-title'>支付方式</div>
              <div className="collection-pay-way-content">
                <Radio.Group onChange={this.payWayChange} size={'large'} value={payWay} buttonStyle="solid">
                  {
                    payWayData.map((v, i) => {
                      return <Radio.Button value={v.value}>{v.icon}{v.title}</Radio.Button>
                    })
                  }
                </Radio.Group>
              </div>
            </div>
            <div className='collection-information' style={{ marginTop: 20 }}>
              <div className='collection-title'>导购员</div>
              <div className="collection-information-content">
                <div className='collection-information-content-item'>
                  <div>导购员</div>
                  <div>
                    <Select allowClear
                      defaultValue={shoppingGuideId}
                      onChange={this.selectChange}
                      placeholder="请选择导购员"
                      style={{ width: 200 }}
                      options={slaesmanData} />
                  </div>
                </div>
              </div>
            </div>
          </div>
        </CashierModal>
        <CashierModal
          title="扫码结算（微信）"
          width={600}
          visible={remoteWeChatResultVisible}
          onCancel={this.remoteWeChatResultDialogClose}
          footer={
            <div className='completion-button-group'>

              <div onClick={this.remoteWeChatResultDialogClose} className='dialog-footer-button'>
                <div>取消收款</div>
              </div>
              <div onClick={this.remoteWeChatDialogSave} className='dialog-footer-button'>
                <div>刷新</div>
              </div>
            </div>
          }
        >
          <Spin spinning={thirdLoading}>
            <div className='third-party-box'>
              <div>请使用微信扫码支付</div>
              <QRCode
                id={'qrid'}
                value={remoteWeChatQrCodeStr}

                size={200} // 二维码的大小
                fgColor="#000000" // 二维码的颜色
                style={{ margin: 'auto' }}
                imageSettings={{ // 二维码中间的logo图片
                  src: logoUrl,
                  height: 40,
                  width: 40,
                  excavate: false, // 中间图片所在的位置是否镂空
                }}
                level="H"
              />
            </div>
          </Spin>
        </CashierModal>
        <CashierModal
          title="扫码结算（支付宝）"
          width={600}
          visible={remoteAlipayResultVisible}
          onCancel={this.remoteAlipayResultDialogClose}
          footer={
            <div className='completion-button-group'>

              <div onClick={this.remoteAlipayResultDialogClose} className='dialog-footer-button'>
                <div>取消</div>
              </div>
              <div onClick={this.remoteAlipayResultDialogSave} className='dialog-footer-button'>
                <div>前去收款</div>
              </div>
            </div>
          }
        >
          <Spin spinning={thirdLoading}>
            <div className='third-party-box'>
              <div>是否确认跳转支付宝二维码收款?</div>
              <div dangerouslySetInnerHTML={{ __html: __html }}></div>
            </div>
          </Spin>
        </CashierModal>
        <CashierModal
          title="现金结算"
          visible={cashVisible}
          onCancel={this.cashDialogClose}
          onOk={this.cashDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>
          <InputNumber
            min={0}
            max={1000000}
            precision={2}
            placeholder="请输入收款金额"
            onChange={this.cashChange}
            onPressEnter={this.cashDialogSave}
            ref={ref => this.cashInputRef = ref}
            value={cashPriceReason}
            style={{ marginBottom: "10px" }}
          />
          <Input
            allowClear
            maxLength={200}
            placeholder='POS机刷卡请备注'
            value={payWayDescription}
            ref={ref => this.payWayDescriptionRef = ref}
            onChange={this.payWayDescriptionChange} />
        </CashierModal>
        <CashierModal
          title="扫码支付（支付宝）"
          visible={remoteAlipayVisible}
          onCancel={this.remoteAlipayDialogClose}
          onOk={this.remoteAlipayDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>

        </CashierModal>
        <CashierModal
          title="扫码支付（微信）"
          visible={remoteWeChatVisible}
          onCancel={this.remoteWeChatDialogClose}
          onOk={this.remoteWeChatDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>

        </CashierModal>
        <CashierModal
          title="余额结算"
          visible={walletVisible}
          onCancel={this.walleDialogClose}
          onOk={this.walletDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>
          <InputNumber
            min={0}
            max={1000000}
            precision={2}
            placeholder="请输入收款金额"
            onChange={this.cashChange}
            onPressEnter={this.walletDialogSave}
            ref={ref => this.cashInputRef = ref}
            value={cashPriceReason}
          />
        </CashierModal>
        <CashierModal
          title="支付宝结算"
          visible={aliPayVisible}
          onCancel={this.alipayDialogClose}
          onOk={this.alipayDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>
          <InputNumber
            min={0}
            max={_.toNumber(React.$transNum(amountPrice, 2, -2))}
            precision={2}
            placeholder="请输入收款金额"
            onChange={this.cashChange}
            onPressEnter={this.alipayDialogSave}
            ref={ref => this.cashInputRef = ref}
            value={cashPriceReason}
          />
        </CashierModal>

        <CashierModal
          title="微信结算"
          visible={weChatVisible}
          onCancel={this.weChatDialogClose}
          onOk={this.weChatDialogSave}
          width={400}
        >
          <div className='amount-price'>应收金额：{<React.$Price price={amountPrice} />}</div>
          <InputNumber
            min={0}
            max={_.toNumber(React.$transNum(amountPrice, 2, -2))}
            precision={2}
            placeholder="请输入收款金额"
            onChange={this.cashChange}
            onPressEnter={this.weChatDialogSave}
            ref={ref => this.cashInputRef = ref}
            value={cashPriceReason}
          />
        </CashierModal>

        <CashierModal
          title="现金找零"
          visible={settlementVisible}
          onCancel={this.settlementDialogClose}
          onOk={this.settlementDialogSave}
          width={400}
        >
          <div className='settlement-box'>
            <div>
              <div>应收金额：{<React.$Price price={amountPrice} />}</div>
              <div>支付金额：{<React.$Price price={React.$transNum(cashPrice, 0, 2)} />}</div>
            </div>
            <div>
              <div>找零：</div>
              {<React.$Price price={differencePrice} color="red" />}
            </div>
          </div>
        </CashierModal>

        <CashierModal
          title="收款结算"
          visible={completionVisible}
          onCancel={this.DialogClose}
          width={1100}

          footer={
            <div className='completion-button-group'>
              <div onClick={() => this.goToDetail()} className='dialog-footer-button'>
                <div>查看订单</div>
              </div>
              <div onClick={this.completionDialogClose} className='dialog-footer-button'>
                <div>返回继续收款</div>
              </div>
            </div>
          }
        >
          <div className='finish-box'>
            <TheImage src={finish} width={256} height={188} preview={false} />
            <div>结算成功</div>
            <div>通过账单可查看详情</div>
          </div>
          <div className='collection-box'>
            <div className='collection-information'>
              <div className='collection-title'>费用结算</div>
              <div className="collection-information-content">
                {
                  collectionData.map(v => {
                    return <div className='collection-information-content-item'>
                      <div>{v.title}</div>
                      <div style={v.style}>{v.value}</div>
                    </div>
                  })
                }
              </div>
            </div>
          </div>
        </CashierModal>

        <CashierModal
          title="三方结算"
          width={600}
          visible={thirdPartyVisible}
          onCancel={this.thirdPartyDialogClose}
          footer={
            <div className='completion-button-group'>
              <div onClick={this.thirdPartyDialogClose} className='dialog-footer-button'>
                <div>取消收款</div>
              </div>
            </div>
          }
        >
          <Spin spinning={thirdLoading}>
            <div className='third-party-box'>
              <TheImage src={thirdParty} width={306} height={188} preview={false} />
              <div>使用扫码枪扫描客户付款码</div>
            </div>
          </Spin>
        </CashierModal>

        <CashierModal
          title="取消收款"
          width={500}
          visible={rejectVisible}
          onCancel={() => this.setState({ rejectVisible: false })}
          footer={
            <div className='completion-button-group'>
              <div style={{ width: 200 }} onClick={() => this.setState({ rejectVisible: false })} className='dialog-footer-button'>
                <div>取消</div>
              </div>
              <div style={{ width: 200 }} onClick={this.rejectDialogSave} className='dialog-footer-button'>
                <div>确认</div>
              </div>
            </div>
          }
        >
          <Spin spinning={rejectLoading}>
            <div style={{ display: 'flex', justifyContent: 'space-between' }}>
              <span>取消原因</span>
              <Input maxLength={30} onChange={this.rejectReamkeChange} style={{ width: 380 }} />
            </div>
          </Spin>
        </CashierModal>
      </div>
    )
  }
}
